<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="设备编号" prop="dev_code">
        <el-input v-model.trim="queryParams.dev_id" placeholder="请输入设备编号" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="上报时间范围" prop="state" label-width="100px">
        <el-date-picker
          v-model="queryParams.value"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          :shortcuts="shortcuts"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
          align="right">
      </el-date-picker>
      </el-form-item>
      <el-form-item label="处理状态" prop="state" label-width="100px">
        <el-select v-model="queryParams.state" clearable placeholder="请选择处理状态" @change="handleQuery"
          style="width: 240px">
          <el-option v-for="item in options1" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :max-height="tableHeight" :data="dataList">
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="所属部门编码" v-if="columns[0].visible" prop="stacode" align="center" width="150" /> -->
      <el-table-column label="设备编号" v-if="columns[0].visible" prop="dev_id" align="center" width="300" />
      <el-table-column label="IMEI" v-if="columns[1].visible" prop="imei" align="center" width="200" />
      <el-table-column label="告警类型" v-if="columns[2].visible" prop="type" align="center" width="200" />
      <el-table-column label="上报时间" v-if="columns[3].visible" align="center" width="200">
        <template #default="scope">
          <span>{{  parseTime(scope.row.ts) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="告警描述" v-if="columns[4].visible" prop="mes" align="center" width="350" />
      <el-table-column label="处理状态" v-if="columns[5].visible" align="center" width="150">
        <template #default="scope">
          <span :class="[scope.row.state === 1?'online':'offline']">{{ scope.row.state==1?'已处理':'未处理' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="240px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleRouter(scope.row)">详情</el-button>
          <el-button link type="success" :disabled="scope.row.state === 1" icon="Edit" @click="handleDelete(scope.row)">处理</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete2(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属监测站" prop="station_id" v-if="form.ent_id">
          <el-select v-model="form.station_id" placeholder="请选择监测站" @change="handleEntChange2">
            <el-option v-for="item in options2" :key="item.id" :label="item.station_Name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属线路" prop="line_code" v-if="form.station_id">
          <el-cascader style="width: 600px;" ref="cascaderRef" @change="handleCascaderChange" v-model="form.line_code"
            :options="options3"
            :props="{ checkStrictly: true,children:'branch_Lines',label:'line_name',value:'line_code'}" />
        </el-form-item>
        <el-form-item label="设备名称" prop="dev_name">
          <el-input v-model.trim="form.dev_name" maxlength="30" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编码" prop="dev_code">
          <el-input v-model.trim="form.dev_code" maxlength="30" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="物联卡号" prop="phone_num">
          <el-input v-model.trim="form.phone_num" maxlength="50" placeholder="请输入物联卡号" />
        </el-form-item>
        <el-form-item label="离线是否报警" label-width="130">
          <el-radio-group v-model="form.offline_alarm_flag">
            <el-radio :value="0">不报警</el-radio>
            <el-radio :value="1">报警</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title2" v-model="open2" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef2" :model="form2" :rules="rules2" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="固件版本号" prop="version">
              <el-input v-model.trim="form2.version" disabled maxlength="30" placeholder="" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务器IP" prop="ip">
              <el-input v-model.trim="form2.ip" maxlength="30" placeholder="请输入服务器IP" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务器端口号" prop="port">
              <el-input v-model.trim="form2.port" maxlength="30" placeholder="请输入服务器端口号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="波特率" prop="baudRate">
              <el-input v-model.trim="form2.baudRate" maxlength="30" placeholder="请输入波特率" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="485地址" prop="addr485">
              <el-input v-model.trim="form2.addr485" maxlength="30" placeholder="请输入485地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过压门限" prop="ratedvoltage">
              <el-input v-model.trim="form2.ratedvoltage" maxlength="30" placeholder="请输入额定电压" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="欠压门限" prop="scalefactor">
              <el-input v-model.trim="form2.scalefactor" maxlength="30" placeholder="请输入比例系数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电压变比" prop="pt">
              <el-input v-model.trim="form2.pt" maxlength="30" placeholder="请输入电压变比" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电流变比" prop="ct">
              <el-input v-model.trim="form2.ct" maxlength="30" placeholder="请输入电流变比" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="零序电流" prop="leakagecurrent">
              <el-input v-model.trim="form2.leakagecurrent" maxlength="30" placeholder="请输入零序电流" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="零序电流变比" prop="shortcircuitcurrent">
              <el-input v-model.trim="form2.shortcircuitcurrent" maxlength="30" placeholder="请输入零序电流变比" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="3U0电压门限" prop="cabinet">
              <el-input v-model.trim="form2.cabinet" maxlength="30" placeholder="请输入3U0电压门限" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进入休眠时间 (秒)" prop="screenidle" label-width="150">
              <el-input v-model.trim="form2.screenidle" maxlength="30" placeholder="请输入进入休眠时间" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="disabled" @click="submitForm2">确 定</el-button>
          <el-button @click="open2=false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useInfoStore } from '@/store/modules/info.js'
const userInfo = useInfoStore();

const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");


const dataList = ref([]);
const open = ref(false);
const open2 = ref(false);
const loading = ref(false);
const disabled = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const title2 = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const menuRef = ref(null);
const options1 = ref([
  { id: 0, name: "未处理" },
  { id: 1, name: "已处理" },
]);
const options2 = ref([]); //监测站点
const options3 = ref([]); //线路列表
const cascaderRef = ref(null);

const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
]
  
// 列显隐信息
const columns = ref([
  { key: 1, label: `设备编号`, visible: true },
  { key: 2, label: `IMEI`, visible: true },
  { key: 3, label: `告警类型`, visible: true },
  { key: 4, label: `上报时间`, visible: true },
  { key: 5, label: `告警描述`, visible: true },
  { key: 6, label: `处理状态`, visible: true },

]);
const data = reactive({
  form: {
    id: null,
    ent_id: null,//企业ID
    dev_name: null,//设备名称
    dev_code: null,//设备编码
    phone_num: null,//设备编码
    offline_alarm_flag: 0,//离线是否报警 0-不报警；1-报警
    offline_alarm_time: 0,//设备编码
    station_id:null,//监测站ID
    line_id:null,//线路ID
    line_code:null,//线路编码
    line_type:0,//线路类型 0-母线；1-支线
    state: null,//是否停用
  },
  form2: {
    version: null,//固件版本号
    id: null,//设备ID
    dev_ID: null,//设备ID
    cid: null,//设备编号
    pwd: null,//设备密码
    ip: null,//服务器IP
    port: null,// 服务器端口号
    baudRate: null,// 波特率
    addr485: null,// 485地址
    ratedvoltage: null,// 过压门限
    scalefactor: null,// 欠压门限
    pt: null,// 电压变比
    ct: null,// 电流变比
    leakagecurrent: null,// 漏电电流
    shortcircuitcurrent: null,// 零序电流变比
    cabinet: null,// 3U0电压门限
    screenidle:null, //休眠时间
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    starTime: null,//开始时间
    endTime: null,//结束时间
    dev_id: '',//设备编号
    state: null,//是否处理：0未处理、1已处理
    value: null,//时间暂存值
    type: null,//报警类型：（11：X轴振速、22：Y轴加速度、30：温度、40：电压、50：信号强度）
  },
  rules: {
    ent_id: [{ required: true, message: "所属企业不能为空", trigger: "blur" }],
    dev_name: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    dev_code: [{ required: true, message: "设备编码不能为空", trigger: "blur" }],
    station_id: [{ required: true, message: "请选择监测站", trigger: "blur" }],
    line_code: [{ required: true, message: "请选择线路", trigger: "blur" }],
  },
  rules2: {
    pwd: [{ required: true, message: "设备密码不能为空", trigger: "blur" }],
    ip: [{ required: true, message: "服务器IP不能为空", trigger: "blur" }],
    port: [{ required: true, message: "服务器端口号不能为空", trigger: "blur" }],
    baudRate: [{ required: true, message: "波特率不能为空", trigger: "blur" }],
    addr485: [{ required: true, message: "485地址不能为空", trigger: "blur" }],
    ratedvoltage: [{ required: true, message: "过压门限不能为空", trigger: "blur" }],
    scalefactor: [{ required: true, message: "欠压门限不能为空", trigger: "blur" }],
    pt: [{ required: true, message: "电压变比不能为空", trigger: "blur" }],
    ct: [{ required: true, message: "电流变比不能为空", trigger: "blur" }],
    leakagecurrent: [{ required: true, message: "零序电流不能为空", trigger: "blur" }],
    shortcircuitcurrent: [{ required: true, message: "零序电流变比不能为空", trigger: "blur" }],
    cabinet: [{ required: true, message: "3U0电压门限不能为空", trigger: "blur" }],
    screenidle: [{ required: true, message: "进入休眠时间不能为空", trigger: "blur" }],
  },

});

const { queryParams, form, form2, rules ,rules2} = toRefs(data);

// 时间范围选中处理 
const handleDateChange = (val) => {
  if (val?.length > 0) {
    queryParams.value.starTime = val[0];
    queryParams.value.endTime = val[1];
  } else {
    queryParams.value.starTime = null;
    queryParams.value.endTime = null;
  }
  getList();
}

// 自定义校验函数
const validateTypeOrSpec = (rule, value, callback) => {
  if (!form.value.types && !form.value.specifications) {
    callback(new Error('型号和规格至少输入一项'));
  } else {
    callback();
  }
};
// 更新校验规则
rules.value.types = { validator: validateTypeOrSpec, trigger: 'blur' };
rules.value.specifications = { validator: validateTypeOrSpec, trigger: 'blur' };

//获取监测站
function handleEntChange(value) {
  // console.log(options1.value);
  proxy.cloudTv_API.GetStationList({
    enterpriseID: value,
  }).then(response => {
    if (response.data?.length > 0) {
      options2.value = response.data || [];
      options2.value.forEach(item => {
        item.station_Name = item.staName;
      });
      if(!form.value.station_id){ //如果监测站无值，则默认第一条
         form.value.station_id = options2.value[0].id;
      }
      getLineList(form.value.station_id);
    }else{
      form.value.station_id = null;
      options2.value =  [];
      form.value.line_code = null;
      options3.value =  [];
      proxy.$modal.msgError("当前企业还没有添加监测站~");
    }
  });
}

//获取监测--母线-支线
function getLineList(value) {
  proxy.cloudTv_API.GetMasterLineList({
    stationID: value,
    state: 1,
  }).then(response => {
    if (response.data?.length > 0) {
      options3.value = response.data || [];
      if(!form.value.line_code){ //如果线路无值，则默认第一条
        form.value.line_code = options3.value[0].line_code;
        form.value.line_id = options3.value[0].id;
      }
    }else{
      form.value.line_code = null;
      form.value.line_id = null;
      options3.value =  [];
      proxy.$modal.msgError("当前监测站还没有线路~");
    }
  });
}

function handleEntChange2(value) {
  form.value.line_code = null;//选中监测站 清空支线
  form.value.line_id = null;
  getLineList(value);
}
  // 主动关闭弹层
function handleCascaderChange(e) {
    // 获取当前选中的节点列表
    const item = cascaderRef.value.getCheckedNodes()[0].data;
    form.value.line_type = item?.master_LineID?1:0;
    form.value.line_id = item.id;
    cascaderRef.value.togglePopperVisible(false)
}
/** 查询列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.ShowPageAlarms(queryParams.value).then(response => {
    dataList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    dt1: null,//开始时间
    dt2: null,//结束时间
    dev_code: '',//设备编号
    state: null,//是否处理：0未处理、1已处理
    value: null,//时间暂存值
  }
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 处理按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm(`是否确认处理设备IMEI${row.imei}-${row.type}的信息?`).then(function () {
    proxy.cloudTv_API.CancelAlarm({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("处理成功");
      });
  })
}
/** 删除操作操作 */
function handleDelete2(row) {
  proxy.$modal.confirm(`是否确认删除设备IMEI${row.imei}-${row.type}的信息?`).then(function () {
    proxy.cloudTv_API.DeleteAlarm({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/role/export", {
    ...queryParams.value,
  }, `role_${new Date().getTime()}.xlsx`);
}


/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
  }
  form.value = {
    id: null,
    ent_id: null,//企业ID
    dev_name: null,//设备名称
    dev_code: null,//设备编码
    phone_num: null,//设备编码
    offline_alarm_flag: 0,//离线是否报警 0-不报警；1-报警
    offline_alarm_time: 0,//设备编码
    station_id:null,//监测站ID
    line_id:null,//线路ID
    line_type:0,//线路类型 0-母线；1-支线
    line_code:null,//线路编码
    state: 1,//是否停用
  };
}
/** 新增物料 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增设备";
}

/** 修改 */
function handleUpdate(row) {
  let newRow = JSON.parse(JSON.stringify(row));
  reset();
  Object.keys(form.value).forEach(key => {
    form.value[key] = newRow[key];
  });
  open.value = true;
  title.value = "修改设备";
  handleEntChange(newRow.ent_id);//获取监测站
}

// 路由跳转 - 详情
function handleRouter(row) {
  const { dev_id,show_ts,ts } = row;
  router.push({
    path: '/public/cloudTv/chartDetails2',
    query: {
      dev_id,
      show_ts,
      ts
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.EditDevice({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddDevice({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 提交按钮 */
function submitForm2() {
  proxy.$refs["roleRef2"].validate(valid => {
    if (valid) {
      proxy.cloudTv_API.UpDateDevCFG({
        ...form2.value,
      }).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        open2.value = false;
      });
    }
  });
}
// 复制
async function copy(text) {
  console.log(text);
  try {
    await navigator.clipboard.writeText(text);
    proxy.$modal.msgSuccess('复制成功');
  } catch (err) {
    console.log(err);

  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getList();

</script>

<style lang="scss" scoped>
.el-input-number {
  width: 190px;
}

.required-star {
  color: #F56C6C;
  margin-right: 4px;
}
.online {
  color: #67C23A;
}

.offline {
  color: #F56C6C;
}
</style>